package com.medical.literature.gateway.filter;

import com.medical.literature.common.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 用户信息过滤器
 * 从JWT token中解析用户信息并添加到请求头中
 */
@Slf4j
@Component
public class UserInfoFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        
        // 从Authorization头中获取JWT token
        List<String> authorizationHeaders = request.getHeaders().get("Authorization");
        if (authorizationHeaders != null && !authorizationHeaders.isEmpty()) {
            String token = authorizationHeaders.get(0);
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7); // 移除"Bearer "前缀
                
                try {
                    // 解析JWT token获取用户信息
                    Claims claims = JwtUtils.parseToken(token);
                    Long userId = claims.get("userId", Long.class);
                    String username = claims.getSubject();
                    Integer userType = claims.get("userType", Integer.class);
                    
                    // 将用户信息添加到请求头中
                    ServerHttpRequest.Builder requestBuilder = request.mutate()
                            .header("X-User-Id", userId.toString())
                            .header("X-Username", username);
                    
                    // 如果userType存在，则添加到请求头中
                    if (userType != null) {
                        requestBuilder.header("X-User-Type", userType.toString());
                    }
                    
                    ServerHttpRequest mutatedRequest = requestBuilder.build();
                    
                    log.info("成功解析用户信息，用户ID: {}, 用户名: {}, 用户类型: {}", userId, username, userType);
                    
                    return chain.filter(exchange.mutate().request(mutatedRequest).build());
                } catch (Exception e) {
                    log.warn("解析JWT token失败: {}", e.getMessage());
                }
            }
        }
        
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0; // 设置过滤器顺序
    }
}